# -*- coding: utf-8 -*-
from psycopg2.pool import ThreadedConnectionPool
import os

class ProcessSafePoolManager:
    def __init__(self, *args, **kwargs):
        self.last_seen_process_id = os.getpid()
        self.args = args
        self.kwargs = kwargs
        self._init()

    def _init(self):
        self._pool = ThreadedConnectionPool(*self.args, **self.kwargs)

    def getconn(self):
        current_pid = os.getpid()
        if not (current_pid == self.last_seen_process_id):
            self._init()
            self.last_seen_process_id = current_pid
        return self._pool.getconn()

    def putconn(self, conn):
        return self._pool.putconn(conn)

def connectpool():
    pool = ProcessSafePoolManager(1, 40, database="QRCODE", user="postgres", password="652684328", host="127.0.0.1", port="5432")
    return pool

def exc_sql(sql_sentence,fetch_type=1):
    pool = connectpool()
    conn = pool.getconn()
    cursor = conn.cursor()
    cursor.execute(sql_sentence)
    if fetch_type == 1:
        data = cursor.fetchall()
    elif fetch_type == 2:
        data = cursor.fetchone()
    else:
        conn.commit()
        data=cursor.rowcount
        #data=None
    cursor.close()
    pool.putconn(conn)
    return data



